package com.hbzhit.modules.job.task;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hbzhit.common.utils.CacheUtils;
import com.hbzhit.common.utils.ConfigConstant;
import com.hbzhit.modules.job.entity.ScheduleJobLogEntity;
import com.hbzhit.modules.job.service.ScheduleJobLogService;
import com.hbzhit.modules.sys.entity.SysLogEntity;
import com.hbzhit.modules.sys.service.SysLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Calendar;

/**
 * 日志清除定时任务
 *
 * @author DING
 */
@Component("logTask")
@Slf4j
public class LogTask implements ITask {
	@Autowired
	private SysLogService sysLogService;
	@Autowired
	private ScheduleJobLogService scheduleJobLogService;

	@Override
	public void run(String params){
		log.debug("logTask定时任务正在执行，参数为：{}", params);
		this.cleanLog(params);
	}

	private void cleanLog(String params) {
		int expireDay = Integer.parseInt(CacheUtils.getConfCache(ConfigConstant.LOG_EXPIRED).getParamValue());
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DATE,  -expireDay);
		String expireDateStr = DateUtil.formatDate(cal.getTime());
		sysLogService.remove(new LambdaQueryWrapper<SysLogEntity>().lt(SysLogEntity::getCreateDate, expireDateStr));
		scheduleJobLogService.remove(new LambdaQueryWrapper<ScheduleJobLogEntity>().lt(ScheduleJobLogEntity::getCreateTime, expireDateStr));
	}
}
